package com.aifast.core.db.handler;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.aifast.common.util.AESUtil;
import com.aifast.core.db.model.Encrypt;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.springframework.stereotype.Component;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @Author fujian
 * @since 2022/1/18 17:38
 */
@Deprecated
@Component
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(Encrypt.class)
public class EncryptTypeHandler extends BaseTypeHandler<Encrypt> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Encrypt encrypt, JdbcType jdbcType) throws SQLException {
        if (ObjectUtil.isNull(encrypt) || StrUtil.isBlank(encrypt.getValue())) {
            preparedStatement.setString(i, null);
            return;
        }
        preparedStatement.setString(i, AESUtil.encryptHex(encrypt.getValue()));
    }

    @Override
    public Encrypt getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return decrypt(resultSet.getString(s));
    }

    @Override
    public Encrypt getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return decrypt(resultSet.getString(i));
    }

    @Override
    public Encrypt getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return decrypt(callableStatement.getString(i));
    }

    private Encrypt decrypt(String value) {
        if (StrUtil.isBlank(value)) {
            return null;
        }
        return Encrypt.builder().value(AESUtil.decryptStr(value)).build();
    }

}
